package cn.tedu.qxhouserent.house.service.impl;

import cn.tedu.qxhouserent.commons.pojo.vo.PageData;
import cn.tedu.qxhouserent.commons.security.LoginPrincipal;
import cn.tedu.qxhouserent.commons.util.PageInfoToPageDataConverter;
import cn.tedu.qxhouserent.house.mapper.UserHouseAppointMapper;
import cn.tedu.qxhouserent.house.pojo.param.UserHouseAppointParam;
import cn.tedu.qxhouserent.house.pojo.vo.UserHouseAppointVO;
import cn.tedu.qxhouserent.house.service.UserHouseAppointService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class UserHouseAppointImpl implements UserHouseAppointService {
    @Autowired
    private UserHouseAppointMapper mapper;

    @Override
    public String yukan(UserHouseAppointParam u, LoginPrincipal l) {
        String dateTime = u.getDateTime();
        Long houseId = u.getHouseId();
        if (l.getId().equals(null) || l.getId().equals("")) {
            String message = "没有用户登录信息，请登录后再试";
            return message;
        }
        if (!u.getPhone().matches("1[3-9]\\d{9}")) {
            String message = "手机号错误，请从新填写";
            return message;
        }
        Long jid = mapper.jid(houseId);
        int d = mapper.countD(dateTime, jid);
        if (d == 1) {
            String message = "经理人已经预约过该时间了，请从新选择时间";
            return message;
        }
        Integer f = mapper.insertApp(l.getId(), u.getHouseId(), u.getName(), u.getPhone(), dateTime);
        if (f == 1) {
            return "预约成功";
        } else return "预约失败";
    }

    @Override
    public PageData<UserHouseAppointVO> yuecha(LoginPrincipal l, Integer page) {
        Integer pageSize = 5;
        return yuecha(l, page, pageSize);
    }

    public PageData<UserHouseAppointVO> yuecha(LoginPrincipal l, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        String d = LocalDateTime.now()+"";
        d=d.replace("T"," ").substring(0,18);
        List<UserHouseAppointVO> list = mapper.yuecha(l.getId(), d);
        PageInfo<UserHouseAppointVO> pageInfo = new PageInfo<>(list);
        PageData<UserHouseAppointVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }
}
